package com.studyroom.controller;

import com.studyroom.common.Result;
import com.studyroom.entity.User;
import com.studyroom.service.UserService;
import com.studyroom.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/file")
public class FileController {

    @Autowired
    private UserService userService;  // 注入用户服务

    @Value("${file.upload.path}")
    private String uploadPath;

    @PostMapping("/upload")
    public Result<String> uploadFile(@RequestParam("file") MultipartFile file, @RequestParam("type") String type) {
        try {
            // 获取当前登录用户
            String username = SecurityUtils.getCurrentUsername();
            User user = userService.getUserByUsername(username);
            if (user == null) {
                return Result.error("用户未登录");
            }

            // 构建用户专属的上传目录
            String userUploadPath = uploadPath + File.separator + "users" + File.separator + user.getId();
            File userDir = new File(userUploadPath);
            if (!userDir.exists()) {
                userDir.mkdirs();
            }

            // 生成文件名
            String originalFilename = file.getOriginalFilename();
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String filename = type + "_" + UUID.randomUUID().toString() + extension;

            // 保存文件
            File dest = new File(userDir.getAbsolutePath() + File.separator + filename);
            file.transferTo(dest);

            // 如果是头像，更新用户头像字段
            if ("avatar".equals(type)) {
                String avatarUrl = "/uploads/users/" + user.getId() + "/" + filename;
                user.setAvatarUrl(avatarUrl);
                userService.updateById(user);
            }

            // 返回文件访问路径
            return Result.success("/uploads/users/" + user.getId() + "/" + filename);
        } catch (IOException e) {
            return Result.error("文件上传失败：" + e.getMessage());
        }
    }
} 